<?php

namespace App\Http\Controllers\Api;

use App\Models\Advice;
use App\Models\Config;
use App\Models\Country;
use App\Models\Member;
use App\Models\Supplier;
use App\Repositories\Api\AdviceRepository;
use App\Repositories\Api\BannerRepository;
use App\Repositories\Api\HotwordsRepository;
use App\Repositories\Api\MemberRepository;
use App\Repositories\Api\SupplierRepository;
use App\Repositories\FileRepository;
use App\Repositories\ParkRepository;
use App\Repositories\PictureMappingRepository;
use App\Repositories\WechatRepository;
use Cache;
use Exception;

class HomeController extends MiniAppController
{
    private $memberRep = NULL;

    public function __construct(
        MemberRepository $memberRep
    )
    {
        parent::__construct();
        $this->memberRep = $memberRep;
    }

    public function index()
    {

        return $this->apiResponse->success([
            'project_name' => '点餐',
            'version' => env('API_VERSION'),
            'date' => date('Y-m-d'),
            'time' => date('Y-m-d H:i:s'),
        ], 'success', 200, []);
    }

    public function config()
    {
        $type = request()->get("type");
        $res = Config::getValue($type);
        return $this->apiResponse->success($res);
    }

    /**
     * 发送短信
     */
    public function send_sms()
    {
        $param = request()->only('mobile');

        $country_id = request()->get('country_id');
        $country_code = Country::where("id", "=", $country_id)->value("code");
        if (!isMobile($param['mobile']) && $country_code == 86) { //中国检验手机号码是否检测
            return $this->apiResponse->error("手机格式错误", 400);
        }

        $sms_cache_key = md5($param['mobile']) . '_sms_code';
        $value = json_decode(Cache::get($sms_cache_key), true);
        if ($value) {
            if (time() - $value['time'] < 120) {
                return $this->apiResponse->error("120s内不要频繁发送", 400);
            }
        }

        $code = get_randomstr(6, 'num');
        Cache::put($sms_cache_key, json_encode(['code' => $code, 'time' => time()]), 120);

        // $content = '您的验证码是：' . $code . ' 请勿泄露，如非你本人操作，请忽略。';
        $res = SendSmsService::send($param['mobile'], $code, $country_code);

        return $this->apiResponse->success([], "已发送");
    }

    /**
     * 投诉
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-10T10:33:19+0800
     */
    public function add_complain()
    {
        $params = request()->only("report_uid", "type", "reason");
        $params['uid'] = UID;
        $params['create_time'] = date("Y-m-d H:i:s");

        $picture_ids = request()->post("picture_ids");
        try {
            if (count($picture_ids) == 0)
                return $this->apiResponse->error("图片必填", 400);

            $complain_id = (new ComplainRepository())->addCompain($params);
            if ($complain_id) {
                (new PictureMappingRepository())->updateMapping($complain_id, "complain", $picture_ids);
            }

            return $this->apiResponse->success([], "投诉成功，我们会尽快处理");
        } catch (Exception $e) {
            return $this->apiResponse->error($e->getMessage(), 400);
        }
    }

    /**
     * @param Request $request
     * 删除文件
     */
    public function delete_file()
    {
        $mid = request()->get('mid', 0);
        if (!$mid) {
            return response([
                'code' => 400,
                'msg' => '参数错误',
                'data' => []
            ], 400);
        }
        $ret = app(FileRepository::class)->removeMapFile($mid);
        return $this->apiResponse->success([], "删除成功");
    }

    /**
     * 上传文件
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-17T18:05:32+0800
     * @return   [type]                   [description]
     */
    public function upload()
    {
        $objectType = (string)request()->object_type;
        $objectId = request()->object_id;
        $subObjectKey = request()->sub_object_key;

        $fileData = request()->file('fileData');
        $res = app(FileRepository::class)->upload($fileData, $objectType, $objectId, $subObjectKey);
        $res['size'] = formatBytes($res['size']);
        $res['full_path'] = getPreviewImage($res['full_path']);

        return response()->json($res);
    }

    /**
     * 绑定手机号码
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-16T14:36:50+0800
     * @return   [type]                   [description]
     */
    public function bind_phone()
    {
        $params = request()->all();
        if (!$params || !isset($params['code'])) {
            return $this->apiResponse->error('参数不完整，可能是当前微信版本过低，请把微信升级到最新版本后重试', 419);
        }

        /*$mobile = Member::where("id", "=", UID)->value('mobile');
        if ($mobile) {
            return retSuc(['mobile' => $mobile]);
        }*/

        $res = (new WechatRepository())->getUserPhoneNumber($params['code']);
        if ($res['errcode'] < 0) {
            return $this->apiResponse->error("系统繁忙", 400);
        }
        if ($res['errcode'] == 40029) {
            return $this->apiResponse->error("不合法的code（code不存在、已过期或者使用过）", 400);
        }
        if ($res['errcode'] == 0) {
            $result = $res['phone_info'];
            Member::where("id", "=", UID)->update([
                'mobile' => $result['purePhoneNumber'],
//                'country' => $c_code
            ]);

            return retSuc(['mobile' => $result['purePhoneNumber']], '获取成功！');
        } else {
            return retFail($res['errmsg']);
        }
    }

    /**
     * 支付异步通知
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-28T21:16:44+0800
     * @return   [type]                   [description]
     */
    public function wx_notify()
    {
        (new WechatRepository())->handleWxNotify();
    }

    // 获取广告位
    public function get_banner()
    {
        $name = request()->get("name");
        if (!$name) {
            return $this->apiResponse->success([]);
        }
        $banners = (new BannerRepository())->getBannerByName($name);
//        $topnavs = (new TopNavRepository())->getList();

        $banners = [
//            ['title' => "", 'link' => "/pages/member/index", "path" => "/Uploads/mini/banner1.png"],
            ['title' => "", 'link' => "/pages/member/index", "path" => "/Uploads/mini/banner4.jpg"],
//           {link: "/pages/member/index", path: "/Uploads/mini/banner.png"},
        ];

        return retSuc([
            'banners' => $banners,
            'tip_pic' => "/Uploads/mini/index_dialog_1.jpg",
        ]);
    }

    /**
     * 餐厅信息
     */
    public function supplier_detail()
    {
        $id = intval(request()->get("id"));
        empty($id) && $id = Member::query()->where('id', UID)->value("shop_supplier_id");

        $res = Supplier::query()->where('id', $id)->first();

        return retSuc(['supplier' => $res]);
    }

    /**
     * 获取指引数据
     */
    public function check_guide()
    {
        $is_guide = Member::query()->where(['id' => UID])->value("guide_amount");
        if ($is_guide >= 3) {
            return retSuc(['is_guide' => 1]);
        }

        $banners = (new BannerRepository())->getBannerByName("index_navs");
        if (empty($banners)) {
            return retSuc();
        }
        Member::query()->where('id', UID)->increment("guide_amount");
        return retSuc(['guide_banner' => $banners[0]['path'] ?? ""]);
    }

    /**
     * 园区列表
     */
    public function park_options()
    {
        return (new ParkRepository())->getOptions();
    }

    /**
     * 投诉 / 建议
     */
    public function add_advice()
    {
        $params = request()->all();
        $created_at = Advice::query()->where(['pid' => 0, 'uid' => UID])->orderby("create_time", "desc")->value('create_time');
        if ($created_at && intval(time() - strtotime($created_at)) < 5) {
            return retFail("不要频繁提交");
        } else {
            if ($params['content']) {
                $data['content'] = trim($params['content']);
                $data['contact_phone'] = trim($params['contact_phone'] ?? NULL);
                $data['object_id'] = intval($params['order_id'] ?? 0);
                $data['type'] = intval($params['type'] ?? 0);
                $data['uid'] = UID;
                $res = Advice::create($data);

                if ($res) {
                    $picture_ids = $params['picture_ids'];
                    if ($picture_ids) {
                        (new PictureMappingRepository())->updateMapping($res['id'], "advice", $picture_ids);
                    }
                    return retSuc([], '感谢反馈');
                } else {
                    return retFail("提交失败");
                }
            } else {
                return retFail("数据异常");
            }
        }
    }


    /**
     * 我的反馈列表
     */
    public function advice_list()
    {
        $filter = [];
        $filter['uid'] = UID;
        $res = (new AdviceRepository())->getReplyList($filter, $this->pageNum, $this->pageSize);
        return retSuc($res);
    }

    public function advice_detail()
    {
        $id = request()->get("id");
        if (!$id)
            return retFail("参数错误");

        $advice = (new AdviceRepository())->getOne($id);
        if (empty($advice))
            return retFail("不存在");

        if ($advice['uid'] != UID)
            return retFail("非法操作");

        return retSuc(['advice' => $advice]);
    }

    /**
     * 商家入驻申请
     */
    public function supplier_apply()
    {
        $mobile = request()->post("mobile", "");

        return (new SupplierRepository())->apply($mobile);
    }

    /**
     *
     */
    public function hotwords()
    {
        $filter = [];
        $shop_id = intval(request()->get("shop_id", 0));
        if ($shop_id) {
            $filter['type'] = 1;
            $filter['shop_id'] = $shop_id;
        } else {
            $filter['type'] = 0;
        }

        $res = (new HotwordsRepository())->getPages($filter, 6, true);
        return retSuc($res);
    }

    /**
     *小程序分享页面
     */
    public function mini_share_list()
    {
//        $res = MiniShare::where(['status' => 1])->get();
        return retSuc(['share_list' => null]);
    }

}

